﻿using AutoMapper;
using MediatR;
using Process.Api.Application.Command;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Model;

namespace Process.Api.Application.Handler
{
    public class AddProcessTypeHandler : IRequestHandler<AddProcessTypeCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<ProcessType> _processRepository;
        private readonly IMapper mapper;
        private readonly ILogger<AddProcessTypeHandler> _logger;

        public AddProcessTypeHandler(IProcessRepository<ProcessType> processRepository, IMapper mapper, ILogger<AddProcessTypeHandler> logger)
        {
            _processRepository = processRepository;
            this.mapper = mapper;
            _logger = logger;
        }
        /// <summary>
        /// 工序分类新增
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async  Task<ApiResult<int>> Handle(AddProcessTypeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var model =mapper.Map<ProcessType>(request);
            model.CreateTime=DateTime.Now;
            model.Creater = "张三";

            var list =_processRepository.GetAllAsync().FirstOrDefault(x=>x.ProcessTypeCode== request.ProcessTypeCode || x.ProcessTypeName==request.ProcessTypeName);
            if(list!=null)
            {
               
                result.Code = ErrorStatus.Error;
                result.Message = "工序分类编号或名称重复";
                return result;
            }
            var res = _processRepository.CreateAsync(model).Result;
            if(res>0)
            {
                _logger.LogInformation("工序分类添加成功");
                result.Code = ErrorStatus.Success;
                result.Message = "工序分类添加成功";
                result.Data = res;
            }
            else
            {
                _logger.LogInformation("工序分类添加失败");
                result.Code = ErrorStatus.Fail;
                result.Message = "工序分类添加失败";
                result.Data = res;
            }
            return result;
        }
    }
}
